package da.metricscraft.client.tools;

import java.awt.Frame;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import da.metricscraft.client.MetricsCraftClient;
import da.metricscraft.client.frames.LoadingPanel;
import da.metricscraft.client.frames.LoadingPanel.Actions;
import da.metricscraft.client.threads.XMLFileFilter;
import da.metricscraft.client.threads.XMLLoader;

public class LoaderRow{
	public JFileChooser fileChooser;
	public JButton refreshButton;
	public JTextField textField;
	public JLabel label;
	public XMLLoader<?> loader;
	public JCheckBox checkBox;
	public String actionname;

	public static ImageIcon ICON_EMPTY;
	public static ImageIcon ICON_REFRESHING;
	public static ImageIcon ICON_REFRESH;
	public static ImageIcon ICON_CHECK;
	public LoaderRow(XMLLoader<?> loader, String actionname){
		refreshButton = new JButton(LoadingPanel.ICON_REFRESH);
		refreshButton.setEnabled(false);
		fileChooser = new JFileChooser("../../");
		fileChooser.setFileFilter(new XMLFileFilter());
		
		textField = new JTextField();
		label = new JLabel(LoadingPanel.ICON_EMPTY);
		checkBox = new JCheckBox();
		checkBox.setEnabled(false);
		checkBox.setVisible(false);
		this.actionname = actionname;
		this.loader = loader;
	}
	public void doAction(Actions a){
		if (a.name().startsWith(actionname)){
			if (a.name().endsWith("SEARCH")){
				fileChooser.showOpenDialog(fileChooser.getParent());
			}else if (a.name().endsWith("REFRESH")){
				load();
			}else if (a.name().equals("CancelSelection")){
				
			}
		}
	}
	public boolean load(){
		if ((new File(textField.getText())).exists()){
			refreshButton.setIcon(LoadingPanel.ICON_REFRESHING);
			refreshButton.setEnabled(false);
			loader.load(textField.getText());
			return true;
		}else{
			JOptionPane.showMessageDialog(MetricsCraftClient.getInstance(), "File not found");
			return false;
		}
	}
	public void finished(){
		label.setIcon(LoadingPanel.ICON_CHECK);
		refreshButton.setIcon(LoadingPanel.ICON_REFRESH);
		refreshButton.setEnabled(true);
	}
	public void approve(){
		textField.setText(fileChooser.getSelectedFile().getAbsolutePath());
		label.setIcon(LoadingPanel.ICON_EMPTY);
	}
}
